<?php

namespace App\SDK\PingAn\service;
use App\SDK\PingAn\library\Request;
use App\SDK\PingAn\library\Config;

class Token
{
    public function get() {
        $result = $this->getByCache();
        if (!$result) {
            $result = $this->getByApi();
            if ($result) {
                $this->saveToCache($result);
            }
        }
        return $result;
    }

    private function getByApi() {
        $result = false;
        $config = Config::get();
        $data = [
            'grantType' => 'client_credentials',
            'scope' => '',
            'clientId' => $config['app_id'],
            'clientSecret' => $config['app_secret'],
        ];
        $url = $config['url']['base'] . $config['url']['token'];
        $response = Request::curlPost($url, json_encode($data));
        if ($response) {
            $result = json_decode($response, true);
        }
        return $result;
    }

    private function getByCache() {
        $result = false;
        $file = __DIR__ . '/../cache/' . md5('token') . '.txt';
        if (is_file($file)) {
            $str = file_get_contents($file);
            if ($str) {
                $data = json_decode($str, true);
                if ((time() + 300) < $data['timeout']) {
                    $result = $data['data'];
                }
            }
        }
        return $result;
    }

    private function saveToCache($data) {
        if ($data['Code'] == '000000') {
            $file = __DIR__ . '/../cache/' . md5('token') . '.txt';
            return file_put_contents($file, json_encode(['data' => $data, 'timeout' => time() + 1800]));
        }
        return false;
    }

    public function removeCache() {
        unlink(__DIR__ . '/../cache/' . md5('token') . '.txt');
    }
}
